<!DOCTYPE html>
<title>Service Worker: UseCounter for page controlled-on-claim</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<script src="resources/usecounter.js"></script>
<script>

promise_test(function(t) {
    var url = 'resources/claim-worker.js';
    var scope = 'resources/blank.html?usecounter-on-claim';
    var worker;
    var frame;

    return service_worker_unregister(t, scope)
      .then(function() { return with_iframe(scope); })
      .then(function(f) {
          frame = f;
          add_completion_callback(function() { frame.remove(); });
          var w = frame.contentWindow;
          assert_equals(w.navigator.serviceWorker.controller, null);
          assert_false(isUseCounted(frame),
                       'should not be counted as controlled yet');
          return navigator.serviceWorker.register(url, {scope: scope});
        })
      .then(function(registration) {
          add_completion_callback(function() { registration.unregister(); });
          worker = registration.installing;
          return wait_for_state(t, worker, 'activated');
        })
      .then(function() {
          var w = frame.contentWindow;
          var saw_controllerchanged = new Promise(function(resolve) {
              w.navigator.serviceWorker.oncontrollerchange = resolve;
            });
          var channel = new MessageChannel();
          var saw_message = new Promise(function(resolve) {
              channel.port1.onmessage = t.step_func(function(e) {
                  assert_equals(e.data, 'PASS', 'claim() should fulfill');
                  resolve();
                });
            });
          worker.postMessage({port: channel.port2}, [channel.port2]);
          return Promise.all([saw_controllerchanged, saw_message]);
        })
      .then(function() {
          var w = frame.contentWindow;
          var controller = w.navigator.serviceWorker.controller;
          assert_true(controller instanceof w.ServiceWorker);
          assert_true(isUseCounted(frame),
                      'should be counted as controlled after claim()');
        });
  }, 'usecounter is counted upon claim() after registration');

</script>
</html>
